package acs.offer.client;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.controller.MessageQueue;
import acs.offer.pojo.Message;
import acs.offer.pojo.TranstractDate;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;
import java.util.Map;

public class ClientHandler  extends SimpleChannelInboundHandler<Message> {
//    private static ChannelGroup channelGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static Map<String,Channel> channelMap=new HashMap<>();
    static Channel channel=null;
//    static ThreadLocal<Channel> channelThreadLocal=new ThreadLocal<Channel>();
    @Override
    protected void channelRead0(ChannelHandlerContext context, Message message) throws Exception {
        System.out.println("收到服务端数据");
        TranstractDate response = JSON.parseObject(message.getContent(), TranstractDate.class);
        switch (response.getResponseEnum()){
            case OFFER_RESPONSE:
                Params params = Params.build();
                params.put(Constant.TRANSFER_OFFER,JSON.parseObject(response.getData().toString(),Map.class));
                params.put(Constant.MESSAGE,message);
                channelMap.put(message.getHeader().getSessionId(),context.channel());
                MessageQueue.getInstance().putMessage(EventType.RESPONSE_FOR_DATA,params);
                break;
        }
        System.out.println(message);
    }
    public static void sendMessage(Message message) {
//        Channel channel = channelMap.remove(message.getHeader().getSessionId());
    	System.out.println("获取时的线程名："+Thread.currentThread().getName());
    	 Channel channel=null;
        if(channel== null){
            channel=ClientHandler.channel;
        }
        channel.writeAndFlush(message);
//        channelGroup.forEach(ch->{
//            ch.writeAndFlush(Message.build(s));
//        });
    }

    //有新连接加入
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channel = ctx.channel();
        System.out.println("保存时的线程名："+Thread.currentThread().getName());
//        channelGroup.add(channel);
    }

}

